import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'package:intl/intl.dart';

class SleepStats extends StatefulWidget {
  final String babyId;
  final DateTimeRange dateRange;

  const SleepStats({Key? key, required this.babyId, required this.dateRange})
    : super(key: key);

  @override
  _SleepStatsState createState() => _SleepStatsState();
}

class _SleepStatsState extends State<SleepStats> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            _buildDailySleepChart(),
            SizedBox(height: 24),
            _buildSleepDistribution(),
            SizedBox(height: 24),
            _buildSleepSummary(),
            SizedBox(height: 24),
            _buildSleepRecordsList(),
          ],
        ),
      ),
    );
  }

  Widget _buildDailySleepChart() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('每日睡眠时长', style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: FutureBuilder<Map<DateTime, double>>(
                future: _calculateDailySleepHours(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(child: CircularProgressIndicator());
                  }

                  final data = snapshot.data!;
                  if (data.isEmpty) {
                    return Center(child: Text('暂无数据'));
                  }

                  return BarChart(
                    BarChartData(
                      alignment: BarChartAlignment.spaceAround,
                      barGroups:
                          data.entries.map((entry) {
                            return BarChartGroupData(
                              x: entry.key.millisecondsSinceEpoch,
                              barRods: [
                                BarChartRodData(
                                  toY: entry.value,
                                  color: Colors.purple,
                                  width: 16,
                                ),
                              ],
                            );
                          }).toList(),
                      titlesData: FlTitlesData(
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              final date = DateTime.fromMillisecondsSinceEpoch(
                                value.toInt(),
                              );
                              return Padding(
                                padding: EdgeInsets.only(top: 8.0),
                                child: Text(
                                  DateFormat('MM/dd').format(date),
                                  style: TextStyle(fontSize: 10),
                                ),
                              );
                            },
                          ),
                        ),
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text('${value.toStringAsFixed(1)}h');
                            },
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSleepDistribution() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('睡眠分布', style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: FutureBuilder<Map<int, double>>(
                future: _calculateHourlyDistribution(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(child: CircularProgressIndicator());
                  }

                  return BarChart(
                    BarChartData(
                      alignment: BarChartAlignment.spaceAround,
                      barGroups: List.generate(24, (index) {
                        return BarChartGroupData(
                          x: index,
                          barRods: [
                            BarChartRodData(
                              toY: snapshot.data![index] ?? 0,
                              color:
                                  (index >= 20 || index <= 6)
                                      ? Colors.indigo
                                      : Colors.purple,
                              width: 12,
                            ),
                          ],
                        );
                      }),
                      titlesData: FlTitlesData(
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text(
                                '${value.toInt()}:00',
                                style: TextStyle(fontSize: 10),
                              );
                            },
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<Map<DateTime, double>> _calculateDailySleepHours() async {
    final records = await DatabaseService().getRecordsByType(
      RecordType.sleep,
      widget.babyId,
      startDate: widget.dateRange.start,
      endDate: widget.dateRange.end,
    );

    Map<DateTime, double> dailyHours = {};
    for (var record in records) {
      final date = DateTime(
        record.timestamp.year,
        record.timestamp.month,
        record.timestamp.day,
      );
      final duration = record.data['duration'] as int;
      dailyHours[date] = (dailyHours[date] ?? 0) + duration / 60;
    }

    return dailyHours;
  }

  Future<Map<int, double>> _calculateHourlyDistribution() async {
    final records = await DatabaseService().getRecordsByType(
      RecordType.sleep,
      widget.babyId,
      startDate: widget.dateRange.start,
      endDate: widget.dateRange.end,
    );

    Map<int, double> hourlyDistribution = {};
    for (var record in records) {
      final hour = record.timestamp.hour;
      final duration = record.data['duration'] as int;
      hourlyDistribution[hour] =
          (hourlyDistribution[hour] ?? 0) + duration / 60;
    }

    return hourlyDistribution;
  }

  Widget _buildSleepSummary() {
    return FutureBuilder<List<HealthRecord>>(
      future: DatabaseService().getRecordsByType(
        RecordType.sleep,
        widget.babyId,
        startDate: widget.dateRange.start,
        endDate: widget.dateRange.end,
      ),
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return SizedBox.shrink();
        }

        final records = snapshot.data!;
        final totalMinutes = records.fold<int>(
          0,
          (sum, record) => sum + (record.data['duration'] as int),
        );
        final avgDaily = totalMinutes / widget.dateRange.duration.inDays / 60;

        return Card(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('睡眠统计', style: Theme.of(context).textTheme.titleLarge),
                SizedBox(height: 16),
                _buildSummaryRow(
                  '总睡眠时长',
                  '${(totalMinutes / 60).toStringAsFixed(1)}小时',
                ),
                _buildSummaryRow('日均睡眠', '${avgDaily.toStringAsFixed(1)}小时'),
                _buildSummaryRow('记录次数', '${records.length}次'),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildSummaryRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label),
          Text(value, style: TextStyle(fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }

  Widget _buildSleepRecordsList() {
    return Card(
      child: FutureBuilder<List<HealthRecord>>(
        future: DatabaseService().getRecordsByType(
          RecordType.sleep,
          widget.babyId,
          startDate: widget.dateRange.start,
          endDate: widget.dateRange.end,
        ),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
          }

          final records = snapshot.data!;
          records.sort((a, b) => b.timestamp.compareTo(a.timestamp));

          return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: records.length,
            itemBuilder: (context, index) {
              final record = records[index];
              final duration = record.data['duration'] as int;
              final hours = duration ~/ 60;
              final minutes = duration % 60;

              return ListTile(
                title: Text('${hours}小时${minutes}分钟'),
                subtitle: Text(
                  DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp),
                ),
                trailing: Text(record.data['notes'] ?? ''),
              );
            },
          );
        },
      ),
    );
  }
}
